from pygame import mixer, time
from pygame.locals import USEREVENT

class Channel:
    def __init__(self):        
        #Inicilializo el modulo para ejecutar sonidos
        mixer.pre_init(44100,16,2,4096)
        mixer.init()  
        self.__canal = mixer.find_channel()
        self.__cola = [] 
        self.__ejecutando_sonidos = False
        self.__end_sound_event = False
        self.__new_sound_event = False
        self.__escuchar = True
        self.SILENCE_CHANNEL = USEREVENT + 4
    
    def get_end_sound_event(self):
        return self.__end_sound_event
    
    def get_new_sound_event(self):
        return self.__new_sound_event
    
    def queue(self,sonido):
        self.__cola.append(sonido)      
    
    def get_queue(self):
        return self.__cola
            
    def __play(self, sonido):
        sonido = mixer.Sound(sonido)
        self.__canal.play(sonido)  
        while self.__canal.get_busy():
            pass
        self.__end_sound_event = True      
    
    def empty_queue(self):
        if len(self.__cola) > 0:
            return False
        else:
            return True
    
    def play_next_sound(self):
        if not self.empty_queue():            
            sonido = self.__cola.pop(0)
            self.__play(sonido)   
            self.__ejecutando_sonidos = True
            return True
        else:
            self.__ejecutando_sonidos = False
            return False
    
    def play_new_sound(self):
        if self.__ejecutando_sonidos:
            return False
        else:
            self.play_next_sound()
            return True
    
    def stop(self):
        self.__canal.stop()
        self.__cola = []
    
    def end(self):
        self.__escuchar = False
        time.wait(50)   
    
    def send_new_sound_event(self):
        self.__new_sound_event = True        
    
    def silence(self):        
        if self.__canal.get_busy() == 1:
            return False
        else:
            if self.empty_queue():
                return True
            else:
                return False
    
    def listen(self):
        while self.__escuchar:
            if self.__end_sound_event:
                self.__end_sound_event = False
                self.play_next_sound()
            if self.__new_sound_event:
                self.__new_sound_event = False
                self.play_new_sound()